﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Data;
using System.IO;

namespace DusonFramework.Documents.Office.Excel.NPOIEx
{
    using NPOI.HSSF.UserModel;
    using NPOI.HPSF;
    using NPOI.SS.UserModel;

    public class Example
    {
        public static void Export2Excel(DataTable dt, string fielddescs, string fields, string exportfilename)
        {
            string filename = exportfilename + ".xls";
            System.Web.HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
            System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            System.Web.HttpContext.Current.Response.HeaderEncoding = System.Text.Encoding.GetEncoding("GB2312");
            System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", filename));

            System.Web.HttpContext.Current.Response.Clear();

            HSSFWorkbook hssfworkbook = new HSSFWorkbook();
            ////create a entry of DocumentSummaryInformation
            DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
            dsi.Company = "EntLib";
            hssfworkbook.DocumentSummaryInformation = dsi;
            ////create a entry of SummaryInformation
            SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
            si.Subject = exportfilename;
            hssfworkbook.SummaryInformation = si;

            #region

            Sheet sheet1 = hssfworkbook.CreateSheet(exportfilename);

            string[] headers = fielddescs.Split(',');
            string[] cellvalues = fields.Split(',');
            Row headerrow = sheet1.CreateRow(0);
            for (int i = 0; i < headers.Length; i++)
            {
                headerrow.CreateCell(i).SetCellValue(headers[i]);

            }

            for (int i = 1; i < dt.Rows.Count; i++)
            {
                Row row = sheet1.CreateRow(i);
                for (int j = 0; j < cellvalues.Length; j++)
                {
                    row.CreateCell(j).SetCellValue(dt.Rows[i][cellvalues[j]].ToString());
                }
            }

            #endregion

            MemoryStream file = new MemoryStream();
            hssfworkbook.Write(file);
            System.Web.HttpContext.Current.Response.BinaryWrite(file.GetBuffer());
            System.Web.HttpContext.Current.Response.End();
        }
    }
}
